from functools import wraps
from apps.resp.response import TOKEN_ERROR

import datetime
import jwt
from django.conf import settings
def jwt_required(view_func):
    @wraps(view_func)
    def _wrapped_view(View,request, *args, **kwargs):
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        if not auth_header.startswith('Bearer '):
            raise TOKEN_ERROR
        token = auth_header.split(' ')[1]
        print(auth_header)
        payload = decode_jwt(token)
        if payload is None:
            raise TOKEN_ERROR
        
        # 将用户信息添加到请求对象中，供视图使用
        request.user_id = payload.get('user_id')
        return view_func(View,request, *args, **kwargs)
    
    return _wrapped_view   

def create_jwt(user_id):
    payload = {
        'user_id': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    }
    return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')

def decode_jwt(token):
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        return payload
    except (jwt.ExpiredSignatureError,jwt.InvalidTokenError) as e:
        raise TOKEN_ERROR